package com.ruoyi.web.controller.scan;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.files.domain.SysFileManage;
import com.ruoyi.files.service.ISysFilesManageService;
import com.ruoyi.opencv.domain.ScanMask;
import com.ruoyi.opencv.service.IServerScanService;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;

import static com.ruoyi.opencv.utils.OpenCVTool.matOfPointToScanMask;
import static org.opencv.imgcodecs.Imgcodecs.imread;

@RestController
@RequestMapping("/scan")
public class ScanTransformController extends BaseController {


    @Autowired
    private ISysFilesManageService fileService;

    @Autowired
    private IServerScanService scanService;

    @PostMapping("/generateMask")
    public AjaxResult generateMask(MultipartFile file) {
        try {
            // 保存文件
            SysFileManage sysFileManage = fileService.saveFile(file);

            // 读取原始图像
            String baseDir = "D:/ruoyi/uploadPath/";
            Mat rawImage = imread(Paths.get(baseDir+sysFileManage.getStoragePath()).toString());

            // 获取轮廓
            MatOfPoint mask = scanService.getMask(rawImage);

            // 轮廓转角点
            ScanMask scanMask = matOfPointToScanMask(mask, sysFileManage.getFileId());

            // 返回结果
            return success(scanMask);
        } catch (Exception e) {
            return error("上传文件失败：" + e.getMessage());
        }
    }

}
